package bank

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"errors"
	"fmt"
	"gorm.io/gorm"
)

// AccountFlowAdd ，新增银行流水
// 1、创建银行流水
// 2、根据账户id修改账户余额
// /**
func AccountFlowAdd(tx *gorm.DB, bankFlow *model.BankFlow) *gorm.DB {

	//创建银行流水
	if err := tx.Create(&bankFlow).Error; err != nil {
		tx.Error = errors.New(sql.ErrorParams)
		return tx
	}

	//修改银行账户金额
	var expr string
	if bankFlow.Type == "收入" {
		expr = "balance + ?"
	} else {
		expr = "balance - ?"
	}
	if err := tx.Model(&model.BankAccount{}).
		Where("id=?", bankFlow.AccountId).
		Updates(map[string]interface{}{
			"balance": gorm.Expr(expr, bankFlow.Money),
		}).Error; err != nil {
		tx.Error = errors.New(sql.ErrorService)
		return tx
	}

	return tx
}

// AccountFlowUpdate ，修改银行流水
// 1、根据流水ID查询要修改的数据
// 2、根据账户id修改账户余额
// /**
func AccountFlowUpdate(tx *gorm.DB, newFlow *model.BankFlow) *gorm.DB {
	// 1、根据流水ID查询要修改的数据
	var oldFlow model.BankFlow
	err := tx.Where("id = ?", newFlow.ID).First(&oldFlow).Error
	if err != nil {
		tx.Error = errors.New(sql.ErrorService + "1")
		return tx
	}

	//2、根据老的银行流水还原账户余额
	var expr string
	if oldFlow.Type == "收入" {
		expr = "balance - ?"
	} else {
		expr = "balance + ?"
	}
	err = tx.Model(&model.BankAccount{}).
		Where("id = ?", oldFlow.AccountId).
		Update("balance", gorm.Expr(expr, oldFlow.Money)).Error
	if err != nil {
		tx.Error = errors.New(sql.ErrorService + "2")
		return tx
	}

	//修改的银行流水
	err = tx.Updates(&newFlow).Error
	if err != nil {
		tx.Error = errors.New(sql.ErrorService + "3")
		return tx
	}

	//根据银行流水修改账户余额
	if newFlow.Type == "收入" {
		expr = "balance + ?"
	} else {
		expr = "balance - ?"
	}
	fmt.Println(expr)
	fmt.Println(newFlow.Money)
	err = tx.Model(&model.BankAccount{}).
		Where("id = ?", newFlow.AccountId).
		Update("balance", gorm.Expr(expr, newFlow.Money)).Error
	if err != nil {
		tx.Error = errors.New(sql.ErrorService + "4")
		return tx
	}
	return tx
}

func AccountFlowDelete(tx *gorm.DB, bankFlowId int) *gorm.DB {
	var bankFlow model.BankFlow
	if err := tx.Where("id = ?", bankFlowId).First(&bankFlow).Error; err != nil {
		tx.Error = errors.New(sql.ErrorService + "1")
		return tx
	}
	if err := tx.Delete(&bankFlow).Error; err != nil {
		tx.Error = errors.New(sql.ErrorService + "2")
		return tx
	}
	var expr string
	if bankFlow.Type == "收入" {
		expr = "balance - ?"
	} else {
		expr = "balance + ?"
	}
	if err := tx.Model(&model.BankAccount{}).
		Where("id = ?", bankFlow.AccountId).
		Update("balance", gorm.Expr(expr, bankFlow.Money)).Error; err != nil {
		fmt.Println(err)
		tx.Error = errors.New(sql.ErrorService + "3")
		return tx
	}
	return tx
}
